<template>
  <div>
    <!-- 搜索栏 -->
    <van-sticky>
      <van-search v-model="searchKeyword" placeholder="请输入搜索关键词" input-align="center" shape="round"
                  @search="searchShops" @input="searchShops" @focus="showSearchAutoComplete = true">
      </van-search>
    </van-sticky>

    <!-- 搜索结果 -->
    <div class="content" v-show="showSearchResults">
      <van-cell v-for="(shop, index) in filteredShops" :key="index" :title="shop.supplierName">
        <template #label>
          <p>地址: {{ shop.address }}</p>
          <p>描述: {{ shop.description }}</p>
          <button @click="viewShopInfo(shop)">查看商店信息</button>
          <button @click="viewShopLocation(shop)" style="margin-left: 10px">查看商店位置</button>
        </template>
      </van-cell>
    </div>

    <div id="container"></div>

    <div id="panel" class="panel" :class="{ 'panel-open': showPanel }">
      <div id="route-panel" class="panel-content">
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import http from "@/plugins/http";
import {Cell as VanCell, Search as VanSearch} from "vant";

export default {
  name: "map-view",
  components: {
    VanSearch,
    VanCell,
  },
  data() {
    return {
      ip: "",
      location: "",
      AMap: null,
      map: null,
      infoWindow: null,
      shops: [],
      filteredShops: [],
      searchKeyword: "",
      showPanel: false,
      showSearchAutoComplete: false,
      showSearchResults:"",
      navigating: false,
      walkingInstance: null,
      drivingInstance: null,
    };
  },
  mounted() {
    this.getIPLocation();
    if (this.$route.params.lat && this.$route.params.lng) {
      this.navigateToLocation(this.$route.params.lat, this.$route.params.lng);
    }
  },
  activated() {
    if (this.map) {
      // 如果地图实例存在，重新调整地图视图
      this.map.setFitView();
    } else {
      // 如果地图实例不存在，重新初始化地图
      this.getIPLocation();
    }
  },
  unmounted() {
    if (this.map) {
      this.map.destroy(); // 销毁地图实例
    }
  },
  methods: {
    viewShopInfo(shop) {
      console.log('Navigating to shop:', shop);
      this.$router.push({ name: 'shops', params: { shop } });
    },
    searchShops() {
      if (this.searchKeyword) {
        this.filteredShops = this.shops.filter((shop) => {
          return shop.supplierName.toLowerCase().includes(this.searchKeyword.toLowerCase());
        });
        this.showSearchResults = this.filteredShops.length > 0;
      } else {
        this.filteredShops = [];
        this.showSearchResults = false;
      }
    },
    getIPLocation() {
      window._AMapSecurityConfig = {
        securityJsCode: "72198c285fce648237253227db71fa27",
      };

      AMapLoader.load({
        key: "60ede0f04543df3c8704fbbab56eea36",
        version: "2.0",
        plugins: ["AMap.CitySearch", "AMap.Geocoder", "AMap.Geolocation"],
      }).then((AMap) => {
        this.AMap = AMap;

        AMap.plugin(["AMap.Geolocation"], () => {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0,
            geocoder: "city",
          });

          geolocation.getCurrentPosition((status, result) => {
            if (status === "complete" && result.info === "SUCCESS") {
              const location = result.position;
              this.location = location;
              this.updateShopCoordinates(location);
              this.initMap(location);
              this.showUserMarker(location);
            } else {
              console.error("获取当前位置失败", result);

            }
          });
        });

      }).catch((error) => {
        console.error("AMap 加载失败:", error);
      });
    },

    initMap(center) {
      this.map = new this.AMap.Map("container", {
        zoom: 16,
        center: center,
      });
      this.map.on("click", (event) => {
        const lngLat = event.lnglat;
        console.log("点击位置经纬度:", lngLat);
        // 这里可以处理经纬度信息，比如显示在页面上或者发送到服务器
      });

      this.infoWindow = new this.AMap.InfoWindow({
        anchor: "top-left",
        content: "",
      });
    },


    showUserMarker(location) {
      const lngLat = new this.AMap.LngLat(location.lng, location.lat);
      this.userMarker = new this.AMap.Marker({
        position: lngLat,
        title: "当前位置",
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
      });
      this.map.add(this.userMarker);
    },

    computeNearbyCoordinates() {
      const nearbyCoordinates = [
        { lng: 118.138133, lat: 24.529881 },
        { lng: 118.11334, lat: 24.510227 },
        { lng: 118.09415, lat: 24.62154 },
        { lng: 118.114361, lat: 24.586803 },
        { lng: 118.0868, lat: 24.494878 },
        { lng: 118.091805, lat: 24.608023 },
        { lng: 118.083729, lat: 24.443645 },
        { lng: 118.158307, lat: 24.443541 },
      ];

      return nearbyCoordinates;
    },

    updateShopCoordinates(centerLngLat) {
      const nearbyCoordinates = this.computeNearbyCoordinates();

      nearbyCoordinates.forEach((nearby, index) => {
        const supplierId = 1000 + index;
        const lng = nearby.lng;
        const lat = nearby.lat;

        this.getAddressFromLngLat(lng, lat)
            .then((address) => {

              http
                  .post(`/supplier/update`, {
                    supplierId: supplierId,
                    lng: lng,
                    lat: lat,
                    address: address,
                  })
                  .then((response) => {
                    if (response.statusCode === "200") {
                      console.log(response.message);
                    } else {
                      console.log(response.message);
                    }
                  })
                  .catch((error) => {
                    console.error("更新商店信息失败:", error);
                  });
            })
            .catch((error) => {
              console.error("获取地址信息失败:", error);
            });
      });

      this.loadShops(centerLngLat);
    },
    viewShopLocation(shop){
      const lngLat = new this.AMap.LngLat(shop.lng, shop.lat);
      this.map.setZoomAndCenter(15, lngLat);
      this.infoWindow.setContent(`
        <div>
          <h3>${shop.supplierName}</h3>
          <p>地址: ${shop.address}</p>
          <p>描述: ${shop.description}</p>
          <button class="navigate-button" data-lng="${shop.lng}" data-lat="${shop.lat}" data-type="walking">步行导航</button>
          <button class="navigate-button" data-lng="${shop.lng}" data-lat="${shop.lat}" data-type="driving">驾车导航</button>
          <button class="cancel-button" data-lng="${shop.lng}" data-lat="${shop.lat}" style="display: none;">取消导航</button>
        </div>
      `);
      this.infoWindow.open(this.map, lngLat);

      this.$nextTick(() => {
        const navigateBtns = document.querySelectorAll(".navigate-button");
        const cancelBtn = document.querySelector(".cancel-button");

        navigateBtns.forEach((btn) => {
          btn.addEventListener("click", () => {
            const lng = parseFloat(btn.getAttribute("data-lng"));
            const lat = parseFloat(btn.getAttribute("data-lat"));
            const type = btn.getAttribute("data-type");

            this.handleNavigateClick(type, lng, lat);
            navigateBtns.forEach((btn) => (btn.style.display = "none"));
            cancelBtn.style.display = "inline-block";
          });
        });

        cancelBtn.addEventListener("click", () => {
          this.handleCancelNavigation();
          cancelBtn.style.display = "none";
          navigateBtns.forEach((btn) => (btn.style.display = "inline-block"));
        });
      });

    },

    getAddressFromLngLat(lng, lat) {
      return new Promise((resolve, reject) => {
        this.AMap.plugin(["AMap.Geocoder"], () => {
          const geocoder = new this.AMap.Geocoder();
          const lngLat = new this.AMap.LngLat(lng, lat);

          geocoder.getAddress(lngLat, (status, result) => {
            if (status === "complete" && result.regeocode) {
              const address = result.regeocode.formattedAddress;
              resolve(address);
            } else {
              reject(result);
            }
          });
        });
      });
    },

    loadShops(location) {

      http
          .get("/supplier/shops", {
            params: { location: location },
            timeout: 10000,
          })
          .then((response) => {
            this.shops = response.data;
            console.log(this.shops.length)
            this.displayShops();
          })
          .catch((error) => {
            console.error("获取商店信息失败:", error);
          });
    },

    displayShops() {
      this.shops.forEach((shop) => {
        const lngLat = new this.AMap.LngLat(shop.lng, shop.lat);
        const marker = new this.AMap.Marker({
          position: lngLat,
          title: shop.supplierName,
        });

        const content = `
          <div>
            <h3>${shop.supplierName}</h3>
            <p>地址: ${shop.address}</p>
            <p>描述: ${shop.description}</p>
            <button class="navigate-button" data-lng="${shop.lng}" data-lat="${shop.lat}" data-type="walking">步行导航</button>
            <button class="navigate-button" data-lng="${shop.lng}" data-lat="${shop.lat}" data-type="driving">驾车导航</button>
            <button class="cancel-button" data-lng="${shop.lng}" data-lat="${shop.lat}" style="display: none;">取消导航</button>
          </div>
        `;

        marker.on("click", () => {
          this.infoWindow.setContent(content);
          this.infoWindow.open(this.map, marker.getPosition());
          this.infoWindow.on("close", () => {
            this.handleCancelNavigation(); // 取消导航
          });
          this.$nextTick(() => {
            const navigateBtns = document.querySelectorAll(".navigate-button");
            const cancelBtn = document.querySelector(".cancel-button");

            navigateBtns.forEach((btn) => {
              btn.addEventListener("click", () => {
                const lng = parseFloat(btn.getAttribute("data-lng"));
                const lat = parseFloat(btn.getAttribute("data-lat"));
                const type = btn.getAttribute("data-type");

                this.handleNavigateClick(type, lng, lat);
                navigateBtns.forEach((btn) => (btn.style.display = "none"));
                cancelBtn.style.display = "inline-block";
              });
            });

            cancelBtn.addEventListener("click", () => {
              this.handleCancelNavigation();
              cancelBtn.style.display = "none";
              navigateBtns.forEach((btn) => (btn.style.display = "inline-block"));
            });
          });
        });

        this.map.add(marker);
      });
    },

    handleNavigateClick(type, lng, lat) {
      this.showPanel = true;

      if (this.navigating) {
        this.clearNavigation();
      }

      switch (type) {
        case "walking":
          this.initWalkingNavigation(lng, lat);
          break;
        case "driving":
          this.initDrivingNavigation(lng, lat);
          break;
        default:
          console.error("未知的导航类型:", type);
          break;
      }
    },

    initWalkingNavigation(lng, lat) {
      this.AMap.plugin(["AMap.Walking"], () => {
        this.walkingInstance = new this.AMap.Walking({
          map: this.map,
          panel: "route-panel",
        });

        this.navigating = true;

        this.walkingInstance.search(
            new this.AMap.LngLat(this.location.lng, this.location.lat),
            new this.AMap.LngLat(lng, lat),
            (status, result) => {
              if (status === "complete") {
                console.log("步行路线搜索完成");
              } else {
                console.error("步行路线搜索失败", result);
              }
            }
        );
      });
    },

    initDrivingNavigation(lng, lat) {
      this.AMap.plugin(["AMap.Driving"], () => {
        this.drivingInstance = new this.AMap.Driving({
          map: this.map,
          panel: "route-panel",
        });

        this.navigating = true;

        this.drivingInstance.search(
            new this.AMap.LngLat(this.location.lng, this.location.lat),
            new this.AMap.LngLat(lng, lat),
            (status, result) => {
              if (status === "complete") {
                console.log("驾车路线搜索完成");
              } else {
                console.error("驾车路线搜索失败", result);
              }
            }
        );
      });
    },

    handleCancelNavigation() {
      this.clearNavigation();
      this.showPanel = false;
      this.$nextTick(() => {
        const navigateBtns = document.querySelectorAll(".navigate-button");
        const cancelBtn = document.querySelector(".cancel-button");
        navigateBtns.forEach((btn) => (btn.style.display = "inline-block"));
        cancelBtn.style.display = "none";
      });
    },

    clearNavigation() {
      if (this.walkingInstance) {
        this.walkingInstance.clear();
      }
      if (this.drivingInstance) {
        this.drivingInstance.clear();
      }
      this.navigating = false;
    },

  },
};
</script>

<style scoped>
#container {
  height: 800px;
  width: 100%;
  z-index: 1; /* Ensure the map is above other elements */
}

.panel {
  position: absolute;
  bottom:140px;
  width: 90%;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  z-index: 1000;
  transition: transform 0.3s ease;
  transform: translateX(-110%);
}
.content {
  position: absolute;
  top: 50px; /* 调整至合适位置 */
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  z-index: 1000;
  width:100%; /* 设置最大宽度，确保不会过宽 */
  overflow-y: auto; /* 如果内容过多，可以滚动 */
}


.panel-open {
  transform: translateX(0);
}


.panel-content {
  max-height: 200px;
  overflow-y: auto;
}


.navigate-button,
.cancel-button {
  margin-top: 10px;
  background-color: #007bff;
  color: #fff;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 4px;
}

.cancel-button {
  background-color: #dc3545;
}
</style>